<template>
  <div class="editor-box">
    <button @click="addBlock('H')">H</button>
    <button @click="addEmbedBlock('E')">E(embed)</button>
    <button @click="addUndeletable('W')">W(不可删)</button>
    <button @click="addLink('链接', 'https://www.baidu.com')">添加链接</button>
    <button @click="addImage">添加图片</button>
    <button @click="addMedia">添加视频</button>
    <button @click="addAudio">添加音频</button>
    <button @click="getData">getData</button>
    <button @click="setData">setData</button>
    <button @click="changeMode">改变模式{{ mode }}</button>
    <div id="editor-wrapper">
      <div id="toolbar-container"><!-- 工具栏 --></div>
      <div id="editor-container"><!-- 编辑器 --></div>
    </div>
    <!-- <video controls> -->
    <!--   <source -->
    <!--     src="http://192.168.3.62:9000/know-video-store/2024/08/14/1723600826778_2024-08-14_268?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=simon%2F20240814%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20240814T020027Z&X-Amz-Expires=604800&X-Amz-SignedHeaders=host&X-Amz-Signature=e8fb31e22ae3d1e1f280323482aad502239fb730fdf3c846ab518e742ad32d23" /> -->
    <!-- </video> -->
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import {
  IDomEditor,
  Boot,
  createEditor,
  createToolbar,
  SlateTransforms,
} from "@wangeditor/editor";
import davinciModule, { hasUndeletableNode } from "./davinci-block";
import davinciLink from "./davinci-link";
import davinciImage from "./davinci-image";
import davinciMedia from "./davinci-media";
// import davinciAttachment from '@wangeditor/plugin-upload-attachment'
import { toolbarKeys } from "./menu-items.js";

let editor: IDomEditor;

//重写删除
const deleteBackward = SlateTransforms.delete;
SlateTransforms.delete = (baseEditor, option) => {
  if (hasUndeletableNode(baseEditor)) return;
  deleteBackward(baseEditor, option);
};

let mode = ref(0);
const changeMode = () => {
  const config = editor.getConfig();
  mode.value = mode.value == 1 ? 0 : 1;
  config.viewMode = mode.value == 1 ? 1 : 0;
  config.hoverbarKeys =
    config.viewMode == 0 ? editModeHoverbarKeys : textModeHoverbarKeys;
  editor.updateView();
  editor.restoreSelection(); // 恢复选区
};

const addBlock = (data: string) => {
  editor.restoreSelection(); // 恢复选区
  editor.insertNode({
    type: "davinci-block",
    content: data,
    undeletable: false,
    prefix: "#",
    brace: true,
    color: "#000",
    attrs: {
      id: "dddd",
      pid: "ppppp",
      class: "davinci-block",
    },
    children: [{ text: "" }],
    // ... 其他字段
  });
};

const addEmbedBlock = (data: string) => {
  editor.restoreSelection(); // 恢复选区
  editor.insertNode({
    type: "davinci-block",
    content: data,
    undeletable: true,
    prefix: "#",
    brace: true,
    color: "#000",
    attrs: {
      'data-woId': "dddd",
    },
    isEmbedSource: true,
    contextmenuCan: true,
    clickCan: true,
    children: [{ text: "" }],
    // ... 其他字段
  });
};

const addUndeletable = (data: string) => {
  editor.restoreSelection(); // 恢复选区
  editor.insertNode({
    type: "davinci-block",
    content: data,
    undeletable: true,
    prefix: "#",
    brace: true,
    color: "#000",
    contextmenuCan: true,
    clickCan: true,
    attrs: {
      id: "dddd",
      pid: "ppppp",
      class: "davinci-block",
    },
    children: [{ text: "" }],
    // ... 其他字段
  });
};
const addLink = (data: string, href: string) => {
  editor.restoreSelection(); // 恢复选区
  editor.insertNode({
    type: "davinci-link",
    content: data,
    href,
    undeletable: false,
    attrs: {
      id: "dddd",
      pid: "ppppp",
      class: "davinci",
    },
    children: [{ text: "" }],
  });
};

const addMedia = () => {
  editor.restoreSelection(); // 恢复选区
  editor.insertNode({
    type: "davinci-media",
    undeletable: false,
    src: "http://192.168.3.62:9000/know-video-store/2024/08/14/1723600826778_2024-08-14_268?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=simon%2F20240814%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20240814T020027Z&X-Amz-Expires=604800&X-Amz-SignedHeaders=host&X-Amz-Signature=e8fb31e22ae3d1e1f280323482aad502239fb730fdf3c846ab518e742ad32d23",
    poster:
      "http://192.168.3.62:9000/know-video-store/know-image-store?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=simon%2F20240814%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20240814T020027Z&X-Amz-Expires=604800&X-Amz-SignedHeaders=host&X-Amz-Signature=8a3024b96450e5af150aed737740cba44d60711f4af418580992dd0224ce95c9",
    color: "#000",
    width: "500",
    suffix: "mp4",
    children: [{ text: "" }],
    // ... 其他字段
  });
};
const addAudio = () => {
  editor.restoreSelection(); // 恢复选区
  editor.insertNode({
    type: "davinci-media",
    undeletable: false,
    src: "http://192.168.3.62:9000/know-video-store/2024/08/14/1723600826778_2024-08-14_268?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=simon%2F20240814%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20240814T020027Z&X-Amz-Expires=604800&X-Amz-SignedHeaders=host&X-Amz-Signature=e8fb31e22ae3d1e1f280323482aad502239fb730fdf3c846ab518e742ad32d23",
    poster:
      "http://192.168.3.62:9000/know-video-store/know-image-store?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=simon%2F20240814%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20240814T020027Z&X-Amz-Expires=604800&X-Amz-SignedHeaders=host&X-Amz-Signature=8a3024b96450e5af150aed737740cba44d60711f4af418580992dd0224ce95c9",
    color: "#000",
    width: "500",
    suffix: "mp3",
    children: [{ text: "" }],
    // ... 其他字段
  });
};
const addImage = () => {
  setTimeout(() => {
    editor.restoreSelection(); // 恢复选区
    editor.insertNode({
      type: "davinci-image",
      undeletable: false,
      src: "https://pic3.zhimg.com/80/v2-f97259929a802be7f72b0f1f2d12c956_720w.webp",
      children: [{ text: "" }],
      alt: "资源内容.jpg",
      content: "资源内容",
    });
  }, 100);
};

const getData = () => {
  let html = editor.getHtml();
  let json = editor.children;
  console.log("html", html);
  console.log("json", json);
  editor.restoreSelection(); // 恢复选区
};

const editModeHoverbarKeys = {
  "davinci-image": {
    menuKeys: [
      "davinci-image-top",
      "davinci-image-middle",
      "davinci-image-bottom",
      "davinci-image-delete",
    ],
  },
  "davinci-media": {
    menuKeys: [
      "davinci-media-top",
      "davinci-media-middle",
      "davinci-media-bottom",
      "davinci-media-edit",
      "davinci-media-delete",
    ],
  },
};

const textModeHoverbarKeys = {
  "davinci-image": {
    menuKeys: [],
  },
  "davinci-media": {
    menuKeys: [],
  },
};

const setData = () => {
  let json = editor.children;
  SlateTransforms.removeNodes(editor);
  SlateTransforms.insertNodes(editor, json);
  editor.updateView();
};

Boot.registerModule(davinciModule);
Boot.registerModule(davinciLink);
Boot.registerModule(davinciImage);
Boot.registerModule(davinciMedia);
// Boot.registerModule(davinciAttachment)
onMounted(async () => {
  const editorConfig = {
    placeholder: "Type here...",
    viewMode: 0, // 0 图文编辑模式  //1 块编辑模式
    EXTEND_CONF: {
      "davinci-block": {
        async onRightClick(elem, deleteNode) {
          console.log('rightclick')
          setTimeout(() => {
            deleteNode();
          }, 1000);
        },
      },
      async getURLWithId(id) {
        console.log('id', id);
        return new Promise((resolve) => {
          setTimeout(() => {
            resolve({
              src: 'https://pic3.zhimg.com/80/v2-f97259929a802be7f72b0f1f2d12c956_720w.webp',
              sourceType: 'Image',
              content: 'title'
            })
          }, 1000)
        })
      },
      "davinci-link": {
        onClick(linkNode) {
          console.log("linkNode", linkNode);
        },
      },
      "davinci-image": {
        async onRightClick(elem, deleteNode) {
          setTimeout(() => {
            deleteNode();
          }, 1000);
        },
        onClick(imageNode) {
          console.log("imageNode", imageNode);
        },
      },
    },
    MENU_CONF: {
      uploadImage: {
        async customUpload(file, insertFn) {
          const { name } = file;
          const promise = new Promise((resolve) => {
            setTimeout(() => {
              resolve(
                "http://47.93.118.248:9000/know-image-store/2024/08/13/1723527366484_2024-08-13_324?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=root%2F20240813%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20240813T053607Z&X-Amz-Expires=604800&X-Amz-SignedHeaders=host&X-Amz-Signature=45d41fe04209d96b4b5e55b14fa4430164d8b67ff1577a071deb8c90cdd3e97e",
              );
            }, 3000);
          });
          const res = await promise;
          insertFn(res, name, "");
        },
      },
      uploadVideo: {
        async customUpload(file, insertFn) {
          fetch("./api.json")
            .then((res) => res.json())
            .then((res) => {
              let src = res.file.url;
              let fileName = res.file.fileName;
              insertFn(src, fileName);
            });
        },
      },
      "davinci-link": {
        checkLink: function (text: string, url: string) {
          try {
            new URL(url);
            return true;
          } catch (err) {
            return "链接地址不正确...";
          }
        },
      },
    },
    hoverbarKeys: {
      "davinci-image": {
        menuKeys: [
          "davinci-image-top",
          "davinci-image-middle",
          "davinci-image-bottom",
          "davinci-image-delete",
        ],
      },
      "davinci-media": {
        menuKeys: [
          "davinci-media-top",
          "davinci-media-middle",
          "davinci-media-bottom",
          "davinci-media-edit",
          "davinci-media-delete",
        ],
      },
    },
  };

  editor = createEditor({
    selector: "#editor-container",
    config: editorConfig,
    mode: "default", // or 'simple'
  });

  let toolConfig = {
    toolbarKeys,
  };

  const toolbar = createToolbar({
    editor,
    selector: "#toolbar-container",
    config: toolConfig,
    mode: "default", // or 'simple'
  });
});
</script>

<style lang="scss">
.editor-box {
  background: #fff;

  &>button {
    background: #fff;
    color: #000;
    border: 1px solid #ccc;
  }
}

#editor-wrapper {
  border: 1px solid #ccc;
  min-height: 800px;
}
</style>
